<template>
  <div class="app-container">
    <!-- 食品介绍 -->
    <el-card class="box-card">
      <h3>食品编辑</h3>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <el-form-item label="食品编号" prop="foodId">
          <el-input v-model="goods.foodId" readonly=""/>
        </el-form-item>
        <el-form-item label="食品名称" prop="foodName">
          <el-input v-model="goods.foodName"/>
        </el-form-item>
        <el-form-item label="食品价格" prop="foodPrice">
          <el-input v-model="goods.foodPrice" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="食品图片">
          <el-upload action="http://localhost:9600/common/upload" list-type="picture" :show-file-list="false"
          ref="upload"
          :on-change="changeImg()"
            :on-success="uploadPicUrl" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
            <!-- <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">

            </div> -->
            <img v-if="goods.foodImg" :src="goods.foodImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <el-image v-for="item in fileList" :key="item.uid" :src="item.url" fit="contain"
            style="max-width:200px; max-height:200px; margin-top:10px;"></el-image>
        </el-form-item>

        <div class="dropdown">
          <template>
            所属商家编号
            <el-select v-model="goods.businessId" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.value" :value="item.value">
              </el-option>
            </el-select>
          </template>
        </div>

        <el-form-item label="备注">
          <el-input v-model="goods.remarks"/>
        </el-form-item>

        <el-form-item label="食品介绍">
          <editor :init="editorInit" v-model="goods.foodExplain"/>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 更新取消按钮 -->
    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleEdit">更新食品</el-button>
    </div>

  </div>
</template>



<script>
import { detailGoods, editGoods, listCatAndBrand } from '@/api/goods/goods'
import { createStorage, uploadPath } from '@/api/system/storage'
import Editor from '@/components/TEditor.vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import { getList } from "@/api/business/bussiness"
export default {
  name: 'GoodsEdit',
  components: { Editor },
  data() {
    return {
      businessIds:[],
      options:[],
      fileList:[],
      uploadPath, // 图片上传路径
      goods: { gallery: [] }, // 食品信息
      // 货品表单
      productForm: {
        id: 0,
        price: 0.0,
        number: 0,
        url: ''
      },

      // 表单验证规则
      rules: {
        goodsSn: [
          { required: true, message: '食品编号不能为空', trigger: 'blur' }
        ],
        name: [{ required: true, message: '食品名称不能为空', trigger: 'blur' }]
      },
      // 富文本编辑器初始化
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: [
          'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
          'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
        ],
        // 上传钩子
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData)
            .then(res => {
              success(res.data.data.url)
            })
            .catch(() => {
              failure('上传失败，请重新上传')
            })
        }
      }
    }
  },
  computed: {
    // 上传请求头
    headers() {
      return {
        'Shopping-Admin-Token': getToken()
      }
    }
  },
  created() {
    // 页面数据初始化
    this.init()
  },
  methods: {
    // 获取数据 ，判断是否有食品id传入
    init: function() {
      if (this.$route.query.id == null) {
        return
      }

      const goodsId = this.$route.query.id
      detailGoods(goodsId).then(response => {
        this.goods = response.data

        this.galleryFileList = []
        for (var i = 0; i < this.goods.gallery.length; i++) {
          this.galleryFileList.push({
            url: this.goods.gallery[i]
          })
        }
        // const keywords = response.data.data.goods.keywords
        // if (keywords !== null) {
        //   this.keywords = keywords.split(',')
        // }
      })

      /* listCatAndBrand().then(response => {
        this.categoryList = response.data.categoryList
        this.brandList = response.data.brandList
      }) */

      getList().then((res) => {

        this.businessList = res.data.records
        console.log(this.businessList);
        this.businessList.forEach( (item, index, array) =>{
	// item数组中的当前项, index当前项的索引, array原始数组；

        this.businessIds.push(item.businessId)
})

        for (let item of this.businessIds) {
          var i = 0
          console.log(item);
          this.options.push({
            label: item,
            value: item

          })
          i+=1;
        }
        console.log(this.options);
      })

    },
    editImg(){
      if(this.goods.foodImg!='' || this.goods.foodImg!=undefined || this.goods.foodImg!=null){
        this.goods.foodImg = null;
      }

    },
    // 取消更新钩子
    handleCancel: function() {
      // this.init()
      // this.$router.go(0) //刷新当前路由页面
      this.$router.push({ path: '/goods/index' })
    },
    // 更新食品钩子
    handleEdit: function() {
      // 构建提交数据
      const finalGoods = this.goods
      // 调用接口
      console.log("dfhgiosdhgiohdighiodshgo",finalGoods);
      editGoods(finalGoods)
        .then(response => {
          this.$notify.success({

            title: '成功',
            message: '更新成功'
          })
          this.$router.push({ path: '/goods/index' })
        })
        .catch(response => {
          MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
            confirmButtonText: '确定',
            type: 'error'
          })
        })
    },

    // 获得焦点钩子
    handleInputConfirm() {
      const newKeyword = this.newKeyword
      if (newKeyword) {
        this.keywords.push(newKeyword)
        this.goods.keywords = this.keywords.toString()
      }
      this.newKeywordVisible = false
      this.newKeyword = ''
    },
    // 获取图片上传路径
    uploadPicUrl: function(response) {

      this.goods.foodImg = response.data
    },

    // 获取图片路径
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.goods.gallery.push(response.data)
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.goods.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.goods.gallery[i] === url) {
          this.goods.gallery.splice(i, 1)
        }
      }
    },

    changeImg(){
      //this.$refs.upload.clearFiles();
    },
    // 上传成功钩子
    uploadProductUrl: function(response) {
      this.productForm.url = response.data.url
    },
    // 确定货品钩子
    handleProductEdit() {
      for (var i = 0; i < this.products.length; i++) {
        const v = this.products[i]
        if (v.id === this.productForm.id) {
          this.products.splice(i, 1, this.productForm)
          break
        }
      }
      this.productVisiable = false
    },

    // 删除食品钩子
    handleAttributeDelete(row) {
      const index = this.attributes.indexOf(row)
      this.attributes.splice(index, 1)
    }
  }
}
</script>



<style>
  .el-card {
    margin-bottom: 10px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>
